package com.shenxuchen.crm.web.controller;

import com.shenxuchen.crm.constant.Constants;
import com.shenxuchen.crm.pojo.Activity;
import com.shenxuchen.crm.pojo.ActivityRemark;
import com.shenxuchen.crm.pojo.User;
import com.shenxuchen.crm.service.ActivityService;
import com.shenxuchen.crm.utils.UUIDUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("act")
public class ActivityController {

    @Resource
    private ActivityService activityService;

    @GetMapping("getAll")
    public List getAll() {
        return activityService.getAll();
    }

    @PostMapping("save")
    public Map save(Activity activity, HttpSession session) {
        activity.setId(UUIDUtils.getUUID());
        User user = (User) session.getAttribute(Constants.LOGIN_USER);
        activity.setCreateBy(user.getLoginAct() + "|" + user.getName());
        activity.setCreateTime(Constants.SDF19.format(new Date()));
        activityService.save(activity);

        return Constants.RESP.SUC_MSG;
    }

    @GetMapping("getById")
    public Activity getById(String id) {
        return activityService.getById(id);
    }

    @PutMapping("edit")
    public Map edit(Activity activity, HttpSession session) {
        User user = (User) session.getAttribute(Constants.LOGIN_USER);
        activity.setEditBy(user.getLoginAct() + "|" + user.getName());
        activity.setEditTime(Constants.SDF19.format(new Date()));
        activityService.edit(activity);
        return Constants.RESP.SUC_MSG;
    }

    @DeleteMapping("delete")
    public Map delete(String[] ids) {
        activityService.delete(ids);
        return Constants.RESP.SUC_MSG;
    }

    @GetMapping("remarks")
    public List remarks(String id) {
        return activityService.getRemarks(id);
    }

    @PostMapping("saveRemark")
    public Map saveRemark(ActivityRemark activityRemark, HttpSession session) {
        User user = (User) session.getAttribute(Constants.LOGIN_USER);
        // 修改
        if (StringUtils.hasText(activityRemark.getId())) {
            activityRemark.setEditPerson(user.getLoginAct() + "|" + user.getName());
            activityRemark.setEditTime(Constants.SDF19.format(new Date()));
            activityService.editRemark(activityRemark);
        }
        // 添加
        else {
            activityRemark.setId(UUIDUtils.getUUID());
            activityRemark.setNotePerson(user.getLoginAct() + "|" + user.getName());
            activityRemark.setNoteTime(Constants.SDF19.format(new Date()));
            activityService.saveRemark(activityRemark);
        }

        return Constants.RESP.SUC_MSG;
    }

    @DeleteMapping("deleteRemark")
    public Map deleteRemark(String id) {
        activityService.deleteRemark(id);
        return Constants.RESP.SUC_MSG;
    }

    @GetMapping("exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取导出的数据
        List<Activity> activities = activityService.getAll();
        /*
            使用POI操作Excel，主要是4个对象
            HSSFWorkbook： excel文件
            HSSFSheet: 标签页
            HSSFRow: 行
            HSSFCell: 单元格
         */

        // 创建Excel对象
        HSSFWorkbook excel = new HSSFWorkbook();
        // 创建标签页
        HSSFSheet sheet = excel.createSheet();
        // 在标签页中创建行:第1行为标题行
        int rowIndex = 0;
        HSSFRow row = sheet.createRow(rowIndex++);
        // 在行内创建单元格
        int cellIndex = 0;
        row.createCell(cellIndex++).setCellValue("名称");
        row.createCell(cellIndex++).setCellValue("所有者");
        row.createCell(cellIndex++).setCellValue("开始日期");
        row.createCell(cellIndex++).setCellValue("结束日期");
        row.createCell(cellIndex++).setCellValue("成本");

        if (activities != null && activities.size() > 0) {
            for (Activity activity : activities) {
                row = sheet.createRow(rowIndex++);
                cellIndex = 0;
                row.createCell(cellIndex++).setCellValue(activity.getName());
                row.createCell(cellIndex++).setCellValue(activity.getOwner());
                row.createCell(cellIndex++).setCellValue(activity.getStartDate());
                row.createCell(cellIndex++).setCellValue(activity.getEndDate());
                row.createCell(cellIndex++).setCellValue(activity.getCost());
            }
        }

        String filename = "市场活动.xls";

        // 通过请求头中的User-Agent来判断浏览器类型
        String ua = request.getHeader("User-Agent");
        boolean IE_LT11 = ua.contains("MSIE"); // IE11以下版本
        boolean IE11 = ua.contains("rv:11.0) like Gecko"); // IE11
        boolean Edge = ua.contains("Edge"); // win10自带的Edge浏览器
        // 如果是微软的浏览器，直接进行UTF-8编码
        if (IE_LT11 || IE11 || Edge) {
            filename = URLEncoder.encode(filename, "UTF-8");
            // 编码之后空格变成+，替换回空格
            filename = filename.replace("+", " ");
        }
        // 标准浏览器使用Base64编码
        else {
            Base64.Encoder encoder = Base64.getEncoder();
            filename = encoder.encodeToString(filename.getBytes("utf-8"));

            // =?utf-8?B?文件名?= 是告诉浏览器以Base64进行解码
            filename = "=?utf-8?B?" + filename + "?=";
        }

        response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
        excel.write(response.getOutputStream());
    }

    @PostMapping("import")
    public Map _import(MultipartFile upFile, HttpSession session) throws Exception {
        HSSFWorkbook excel = new HSSFWorkbook(upFile.getInputStream());
        HSSFSheet sheet = excel.getSheetAt(0);
        int rowIndex = 1;

        User user = (User) session.getAttribute(Constants.LOGIN_USER);
        String createBy = user.getLoginAct() + "|" + user.getName();
        String createTime = Constants.SDF19.format(new Date());

        List<Activity> activities = new ArrayList<>();

        HSSFRow row;
        while ((row = sheet.getRow(rowIndex++)) != null) {
            Activity activity = new Activity();
            activity.setId(UUIDUtils.getUUID());
            activity.setCreateBy(createBy);
            activity.setCreateTime(createTime);
            int cellIndex = 0;
            activity.setName(row.getCell(cellIndex++).getStringCellValue());
            activity.setOwner(row.getCell(cellIndex++).getStringCellValue());
            activity.setStartDate(row.getCell(cellIndex++).getStringCellValue());
            activity.setEndDate(row.getCell(cellIndex++).getStringCellValue());
            activity.setCost(row.getCell(cellIndex++).getStringCellValue());

            activities.add(activity);
        }

        if (activities.size() > 0) {
            activityService.saveList(activities);
        }
        return Constants.RESP.SUC_MSG;
    }
}
